package com.rongc.client.freight.business.mine.view.activity;

import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.flyco.dialog.entity.DialogMenuItem;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.NormalListDialog;
import com.rongc.client.core.exception.RegexException;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.KeyboardUtil;
import com.rongc.client.core.utils.LogUtils;
import com.rongc.client.core.utils.RegexUtil;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.request.result.NullResult;
import com.rongc.client.freight.business.mine.request.api.CashoutApi;
import com.rongc.client.freight.business.mine.view.adapter.RecyclerKeyboardAdapter;
import com.rongc.client.freight.business.mine.view.popup.MinePopup;
import com.rongc.client.freight.utils.UtilMethod;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by ccqx on 2017/7/17.
 */

public class TixianActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.tv_bank)
    TextView mTvBank;
    @Bind(R.id.et_balance)
    EditText mEtBalance;
    @Bind(R.id.tv_balance_tip)
    TextView mTvBalanceTip;

    NormalListDialog dialog ;
    ArrayList<DialogMenuItem> banks;

    List<String> pwdDatas = new ArrayList<>();
    PopupWindow popupWindowPay;

    Response.Listener<NullResult> respOrderListener = new Response.Listener<NullResult>() {

        @Override
        public void onResponse(NullResult response) {
            if (HandleCode.requestSuccess()) {

                ActivityUtils.toast("提现成功等待审核");
                finish();
            } else {
                UtilMethod.dismissProgressDialog(TixianActivity.this);
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            LogUtils.i("error.getMessage(): " + error.getMessage());
            UtilMethod.dismissProgressDialog(TixianActivity.this);
        }
    };

    @OnClick({R.id.tv_bank,R.id.btn_submit,R.id.tv_all})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_close:
                popupWindowPay.dismiss();
                break;
            case R.id.tv_forget:
                ActivityUtils.startActivity(this,PasswordPayActivity.class);
                break;
            case R.id.tv_bank:
                dialog.show();
                break;
            case R.id.btn_submit:
                try{
                    prepare();

                    pwdDatas.clear();
                    ((TextView)popupWindowPay.getContentView().findViewById(R.id.tv_total)).setText(
                            String.format(getResources().getString(R.string.tixian_popup_total),
                                    mEtBalance.getText().toString()));

                    popupWindowPay.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

                }catch (RegexException e){
                    ActivityUtils.toast(e.getMessage());
                }
                break;
            case R.id.tv_all:
                mEtBalance.setText(UniApplication.getInstance().getUserInfo().getBalance());
                break;
        }
    }

    void prepare() throws RegexException {
        if (!RegexUtil.checkNotNull(mEtBalance.getText().toString())) {
            throw new RegexException("请输入提现余额");
        } else if (!RegexUtil.checkNotNull(mTvBank.getText().toString())) {
            throw new RegexException("请选择提现银行");
        }else if (StringUtils.parseInt(mEtBalance.getText().toString()) < 100) {
//            throw new RegexException("提现金额必须大于100元哟");
            throw new RegexException("低于100元无法提现哟");
        }
    }

    void makeBanklist(){
        banks.clear();
        if(StringUtils.isNotEmpty(UniApplication.getInstance().getUserInfo().getBankcard())){
            String bankStr = StringUtils.getBankStr(UniApplication.getInstance().getUserInfo().getBankcard(),
                    UniApplication.getInstance().getUserInfo().getBanktype());

            banks.add(new DialogMenuItem(bankStr,1));
        }
        banks.add(new DialogMenuItem("添加银行卡提现",0));
        dialog.setData(banks);

    }

    @Override
    public void onResume() {
        super.onResume();
        makeBanklist();
    }

    @Override
    public void initView() {
        initToolbar(R.string.tixian_title);

        banks = new ArrayList<>();
        mTvBalanceTip.setText(Html.fromHtml(String.format(getResources().getString(R.string.tixian_balance_tip),
                UniApplication.getInstance().getUserInfo().getBalance())));


        makeDialog();
        makePayPopup();
    }

    public void makeDialog(){
        dialog = new NormalListDialog(this,banks);
        dialog.title("选择银行卡")
                .layoutAnimation(null)
                .setOnOperItemClickL(new OnOperItemClickL() {
                    @Override
                    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if(banks.get(position).mResId == 0){
                            ActivityUtils.startActivity(TixianActivity.this,BankAddActivity.class);
                            dialog.cancel();
                        }else{
                            dialog.cancel();
                            mTvBank.setText(banks.get(position).mOperName);
                        }
                    }
                });
    }

    public void makePayPopup(){
        final RecyclerKeyboardAdapter mAdapter = new RecyclerKeyboardAdapter(this,pwdDatas);
        popupWindowPay = MinePopup.makePopupPayTxOption(this, mAdapter, this, new KeyboardUtil.KeyBoardListener() {
            @Override
            public void onChange() {
                if(mAdapter.getDatas().size() <= 6)
                    mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onComplete() {
//                if(mAdapter.getData().equals(UniApplication.getInstance().getUserInfo().getPayPwd()) ) {
                    RequestManager.getInstance().call(new CashoutApi(new CashoutApi.CashoutParams(
                            mEtBalance.getText().toString(), mAdapter.getData()),
                            respOrderListener, errorListener));

                    popupWindowPay.dismiss();
//                }else
//                    ActivityUtils.toast("密码错误");
            }
        });
        popupWindowPay.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f; // 0.0-1.0
                getWindow().setAttributes(lp);
            }
        });
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_tixian;
    }
}
